package com.wbdgj.ui.store.cafe;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.CompaignAdapter;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.base.BaseFragment;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.booking.BookingInfoActivity;
import com.wbdgj.ui.branch.BranchDetailActivity;
import com.wbdgj.ui.branch.NetfeeRoamingActivity;
import com.wbdgj.ui.home.MapDialogAtivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.store.PointsMallActivity;
import com.wbdgj.ui.store.StoreCofeActivity;
import com.wbdgj.ui.word_compaign.WordCompaignActivity;
import com.wbdgj.utils.ContextUtils;
import com.wbdgj.utils.ListViewForScrollView;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

public class StoreCofeFragment01 extends BaseFragment implements PtrHandler {

    private Context context;

    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;

    @BindView(R.id.scrollView)
    ScrollView scrollView;

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.collection)
    ImageView collection;
    @BindView(R.id.branchName)
    TextView branchName;
    @BindView(R.id.BRANCH_AVG)
    TextView BRANCH_AVG;
    @BindView(R.id.compaignList)
    ListViewForScrollView compaignList;
    private CompaignAdapter compaignAdapter;
    private String phoneTxt;

    private String BRANCH_ID, zoneName;
    private String COORDSX, COORDSY;
    private String TYPE;
    private ArrayList<String> localImages = new ArrayList<String>();

    @BindView(R.id.lswk)
    TextView lswk;

    @BindView(R.id.myImg)
    ImageView myImg;
    @BindView(R.id.ycxjImg)
    ImageView ycxjImg;

    @Override
    protected int getLayout() {
        return R.layout.ui_story_cofe_fragment_01;
    }

    @Override
    protected void onInit() {
        context = getActivity();
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        pfl_root.disableWhenHorizontalMove(true);

        BRANCH_ID = BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.HOTEL_ID);
        queryBranch();
        appbranchactivity();
        isopenRoam();

        compaignList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                if (!compaignAdapter.hasNoData){
                    startActivity(new Intent(context, WordCompaignActivity.class).putExtra("id", compaignAdapter.getItem(i).get("cloud_id")+""));
                }
            }
        });
    }

    @Override
    public void fetchData() {

    }

    @OnClick({R.id.dh, R.id.call, R.id.cwfLay, R.id.dzLay, R.id.myLay, R.id.ycxjLay, R.id.jfscLay, R.id.collection})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.collection:
                if (TYPE.equals("")){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定关注吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            addAttention();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定取消关注吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            delAttention();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.cwfLay:
                ToastUtils.toastShort("暂未开放");
                break;
            case R.id.dzLay:
                ToastUtils.toastShort("暂未开放");
                break;
            case R.id.myLay:
                if (isRoam){
                    startActivityForResult(new Intent(context, NetfeeRoamingActivity.class).putExtra("id", BRANCH_ID)
                            .putExtra("name", zoneName),1);
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "当前门店没有开通此功能！", 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }

                break;
            case R.id.ycxjLay:
                final ConfirmDialog confirmDialogbalance = new ConfirmDialog(context, "确定下机吗？", 1);
                confirmDialogbalance.show();
                confirmDialogbalance.setCanceledOnTouchOutside(false);
                confirmDialogbalance.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        confirmDialogbalance.dismiss();
                        balance();
                    }

                    @Override
                    public void doCancel() {
                        confirmDialogbalance.dismiss();
                    }
                });
                break;
            case R.id.jfscLay:
                launch(PointsMallActivity.class);
                break;

            case R.id.dh:
                if (TextUtils.isEmpty(COORDSX)){
                    Uri uri = Uri.parse("amapuri://route/plan/?dlat="+""+"&dlon="+""+"&dname="+branchName.getText().toString()+"&dev=0&t=0");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                }else{
                    startActivity(new Intent(context, MapDialogAtivity.class).putExtra("COORDSX", COORDSX).putExtra("COORDSY", COORDSY));
                }
                break;
            case R.id.call:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(context,
                            Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 10);
                    }else{
                        Intent intent =new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phoneTxt));
                        startActivity(intent);
                    }
                }else{
                    Intent intent =new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneTxt));
                    startActivity(intent);
                }
                break;
        }
    }

    private void balance() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().balance(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else if(userModelBaseResultModel.getResultCode().equals("0404")){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "自助下机失败！", 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    private void appbranchactivity() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().appnbnactivity(BRANCH_ID, "2");
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    ArrayList<LinkedTreeMap> arrayList = (ArrayList<LinkedTreeMap>) linkedTreeMap.get("data");
                    compaignAdapter = new CompaignAdapter(context, arrayList);
                    compaignList.setAdapter(compaignAdapter);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void queryBranch() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().queryBranch(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();

                    if (linkedTreeMap.containsKey("TAB")){
                        lswk.setText(linkedTreeMap.get("TAB")+"");
                    }else{
                        lswk.setText("单体门店");
                    }

                    if (linkedTreeMap.containsKey("COORDSY")){
                        COORDSY =  linkedTreeMap.get("COORDSY")+"";
                    }
                    if (linkedTreeMap.containsKey("COORDSX")){
                        COORDSX =  linkedTreeMap.get("COORDSX")+"";
                    }

                    if (linkedTreeMap.containsKey("BRANCH_PHONE")){
                        phoneTxt = linkedTreeMap.get("BRANCH_PHONE") +"";
                        phone.setText("电话："+ linkedTreeMap.get("BRANCH_PHONE"));
                    }else{
                        phone.setText("电话：");
                    }

                    if (linkedTreeMap.containsKey("ADDRESS")){
                        address.setText("地址："+linkedTreeMap.get("ADDRESS")+"");
                    }else{
                        address.setText("地址：");
                    }


                    if ((linkedTreeMap.get("TYPE")+"").equals("null")){
                        TYPE = "";
                        collection.setImageResource(R.mipmap.branch_detail_collection);
                    }else{
                        TYPE = "1";
                        collection.setImageResource(R.mipmap.branch_detail_collection_f);
                    }

                    if (!(linkedTreeMap.get("BRANCH_AVG")+"").equals("null")){
                        BRANCH_AVG.setText("人均"+decimalFormat.format(linkedTreeMap.get("BRANCH_AVG"))+"元/小时");
                    }else{
                        BRANCH_AVG.setText("人均元/小时");
                    }


                    branchName.setText(linkedTreeMap.get("NAME")+"");
                    zoneName = linkedTreeMap.get("NAME") +"";

                    if ((linkedTreeMap.get("TYPE")+"").equals("null")){
                        TYPE = "";
                        collection.setImageResource(R.mipmap.branch_detail_collection);
                    }else{
                        TYPE = "1";
                        collection.setImageResource(R.mipmap.branch_detail_collection_f);
                    }

                    localImages = new ArrayList<>();
//                    if (linkedTreeMap.containsKey("IMG_URL_ONE")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_ONE"));
//                    }
//                    if (linkedTreeMap.containsKey("IMG_URL_TWO")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_TWO"));
//                    }
//                    if (linkedTreeMap.containsKey("IMG_URL_THREE")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_THREE"));
//                    }
//                    if (linkedTreeMap.containsKey("IMG_URL_FOUR")){
                        localImages.add(HttpAdapter.HEAD_URL +linkedTreeMap.get("IMG_URL_FOUR"));
//                    }

                    convenientBanner.setPages(new CBViewHolderCreator() {
                        @Override
                        public Object createHolder() {
                            return new LocalImageHolderView();
                        }
                    },localImages)
                            //设置指示器是否可见
                            .setPointViewVisible(true)
                            //设置自动切换（同时设置了切换时间间隔）
                            .startTurning(3000)
                            //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                            .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                            //设置指示器的方向（左、中、右）
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                            //设置点击监听事件
                            //                .setOnItemClickListener(this)
                            //设置手动影响（设置了该项无法手动切换）
                            .setManualPageable(true);

                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    //为了方便改写，来实现复杂布局的切换
    private class LocalImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(context).load(data).placeholder(R.mipmap.detail_wait).error(R.mipmap.detail_error).into(imageView);
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        queryBranch();
        appbranchactivity();
        isopenRoam();
        pfl_root.refreshComplete();
    }

    private void addAttention() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().addAttention(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("关注成功！");
                    queryBranch();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void delAttention() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().delAttention(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("取消关注成功！");
                    queryBranch();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private boolean isRoam = true;

    private void isopenRoam() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().isopenRoam(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    myImg.setImageResource(R.mipmap.store_my_icon);
                    isRoam = true;
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    myImg.setImageResource(R.mipmap.store_my_icon2);
                    isRoam = false;
                }
            }
        });
    }
}
